<?php
class ActiveRecord extends CActiveRecord {

    public $id_;
    public $userId_;
    public $accountId_;
    public $language_;
    public $keywords_;
    public $limit_;
    public $pageSize_ = 10;
    public $page_;
    public $captcha_;
    public $var_ = ''; // for security
    
    public $image_;
    public $imageUrl_;
    public $imageEmbed_;
    public $imageEditor_;
    
    public $file_;
    public $video_;
    public $videoEditor_;
    
    public $defaultWidth;
    public $defaultHeight;
    public $defaultImage;
    public $defaultCoverImage;
    public $defaultLanguage='en';
    
    public $oldParent_;
    public $oldPosition_;
    public $dataLog;
    
    protected $_transaction;
    
    
    public function urlFormat($value) {
        return Yii::app()->format->urlText($value);
    }

    public function keywordFormat($value) {
        return empty($value)? null: strtolower(Yii::app()->format->keyword($value));
    }

    public function currencyFormat($value) {
        return Yii::app()->format->currency($value);
    }

    public function textToUrl($string, $noFollow = true, $newWindow = true){
        return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\" target=\"_blank\">\\0</a>", $string);        
    }
    
    public function getCurrentTimestamp(){
    	return new CDbExpression('NOW()');
    }
    
    public function getCurrentDateTime($php=false) {
        return $php? date('Y-m-d H:i:s', time()): new CDbExpression('NOW()');
    }

    public function getCurrentDate(){
    	return new CDbExpression('NOW()');
    }
    
    public function getCurrentTime(){
    	return new CDbExpression('NOW()');
    }
    
    public function getCurrentTimeZone(){
    	return date_default_timezone_get();
    }
    
	public function setCreateDateTime(){
		$this->create_timezone = $this->update_timezone = $this->currentTimeZone;
		$this->create_timestamp = $this->update_timestamp = $this->currentTimestamp;
		$this->create_datetime = $this->update_datetime = $this->currentDateTime;
		$this->create_date = $this->update_date = $this->currentDate;
		$this->create_time = $this->update_time = $this->currentTime;
		$this->create_by = $this->update_by = $this->userId;
	}    
    
	public function setUpdateDateTime(){
		$this->update_timezone = $this->currentTimeZone;
		$this->update_timestamp = $this->currentTimestamp;
		$this->update_datetime = $this->currentDateTime;
		$this->update_date = $this->currentDate;
		$this->update_time = $this->currentTime;
		$this->update_by = $this->userId;
	}
	
    public function getCurrentPHPDateTime(){
        return date(Yii::app()->params['dateFormat']);
    }

    public function getUserId() {
        return Yii::app()->user->isGuest ? 0 : Yii::app()->user->id;
    }

    public function getStatusCode(){
        return (int)$this->status_code;
    }
    
    public function getStatus(){
        switch($this->status_code){
            case Option::STATUS_AS_ACCOUNT:
                return empty($this->account)? null: $this->account->status;
                break;
            case Option::STATUS_AS_USER: 
                return empty($this->creator)? null: $this->creator->status;
                break;
            default:
                return Option::recordStatus((int)$this->status_code);
                break;
        }
    }
    
    public function getIsDependentStatus(){
        return !$this->isNewRecord && in_array($this->status_code, array(Option::STATUS_AS_ACCOUNT, Option::STATUS_AS_USER));
    }
    
    /**
     * Author
     * @return type
     */
    public function getCreatorId(){
        return empty($this->creator)? null: $this->creator->id;
    }
    
    public function getCreatorSquareAvatar(){
        return empty($this->creator)? null: $this->creator->squareAvatar;
    }
    
    public function getCreatorLargeSquareAvatar(){
        return empty($this->creator)? null: $this->creator->largeSquareAvatar;
    }
    
    public function getCreatorAvatar(){
        return empty($this->creator)? null: $this->creator->avatar;
    }
    
    public function getCreatorSmallAvatar(){
        return empty($this->creator)? null: $this->creator->smallAvatar;
    }
    
    public function getCreatorMediumAvatar(){
        return empty($this->creator)? null: $this->creator->mediumAvatar;
    }
    
    public function getCreatorOriginalAvatar(){
        return empty($this->creator)? null: $this->creator->originalAvatar;
    }
    
    public function getCreatorUrl(){
        return empty($this->creator)? 'javascript:void(0);': $this->creator->url;
    }
    
    public function getCreatorName() {
        return empty($this->creator) ? Lang::t('app.anonymous') : $this->creator->displayName;
    }

    public function getCreatorRole(){
        return empty($this->creator)? null:$this->creator->role;
    }
    
    public function getCreatedTime() {
        return strtotime($this->create_time);
    }
    
    public function getCreatedTimeAgo(){
        return Time::timeAgo(strtotime($this->create_time));
    }

    public function getEditorId() {
        return empty($this->editor) ? null : $this->editor->id;
    }
    
    public function getEditorName() {
        return empty($this->editor) ? Lang::t('app.anonymous') : $this->editor->displayName;
    }

    public function getModifierRole(){
        return empty($this->editor)? null :$this->editor->role;
    }
    
    public function getUpdatedTime() {
        return strtotime($this->update_time);
    }
    
    public function getModifiedTimeAgo(){
        return Time::timeAgo(strtotime($this->update_time));
    }

    public function getUrl() {
        //return 'javascript:void(0);';
        $controller = get_class($this);
        $controller[0] = strtolower($controller[0]);
        $params = array('id' => $this->id);
        // add the title parameter to the URL
        if ($this->hasAttribute('title'))
            $params['title'] = $this->title;
        return Yii::app()->urlManager->createUrl($controller . '/view', $params);
    }

    /*
     * transaction
     */
    public function beginTransaction() {
        $this->_transaction = $this->dbConnection->beginTransaction();
    }

    public function commit() {
        $this->_transaction->commit();
    }

    public function rollback() {
        $this->_transaction->rollback();
    }

    /*
     * share function
     */
    public function truncateWrapText($string, $length, $width, $break=" ", $cut=true){
        //truncates a string to a certain char length, stopping on a word if not specified otherwise.
        if (strlen($string) > $width) {
            $string = filter_var($string, FILTER_SANITIZE_STRING);
            $string = substr($string,0,($length -3));
            return wordwrap($string, $width, $break, $cut).'...';
        }
        return $string;
    }
    
    
    public function getChildren($parent = 0, $lvl = 0) {
        $criteria = new CDbCriteria;
        $criteria->compare('parent_id', $parent);
        $criteria->order = 'position ASC';
        $models = $this->accessible()->findAll($criteria);
        $prefix = str_repeat('&nbsp;&nbsp;&nbsp;',  ++$lvl) . '>&nbsp;';
        foreach ($models as $data) {
            echo '<br />' . $prefix . $data->title;
            $this->getChildren($data->id, $lvl);
        }
    }

    /**
     * 
     * @param type $id
     * @param type $newPosition
     * @param type $parent
     * @return type
     */
    public function updateToPosition($id, $newPosition, $parent=0){
        return $this->updateByPk($id, array('position'=>$newPosition), 'parent_id = :parent', array(':parent'=>$parent));
    }
    
    public function updatePosition($condition=null){
        switch ($this->scenario) {
            case 'adminCreate':
            case 'userCreate':
                $this->updateCounters(array('position' => 1), array_filter(array(
                    'scopes'=>array('accessible'),
                    'condition'=>implode(' AND ',array_filter(array(
                        'parent_id = '.$this->parent_id,
                        $condition,
                    ))),
                )));
                break;
            case 'adminUpdate':
                
                if($this->oldParent_===null && empty($this->oldPosition_)) break ;
                
                // update old parent children
                $this->updateCounters(array('position'=>-1), array(
                    'scopes'=>array('accessible'),
                    'condition'=>implode(' AND ',array_filter(array(
                        'parent_id = '.$this->oldParent_,
                        'position > '.$this->oldPosition_,
                        $condition,
                    ))),
                ));
                
                // update new parent children
                $this->updateCounters(array('position' => 1), array_filter(array(
                    'scopes' => array('accessible'),
                    'condition'=>implode(' AND ',array_filter(array(
                        'parent_id = '.$this->parent_id,
                        $condition,
                    ))),
                )));
                break;
            case 'adminDelete':
            case 'userDelete':                
                // update old parent children
                $this->updateCounters(array('position'=>-1), array(
                    'scopes'=>array('accessible'),
                    'condition'=>implode(' AND ',array_filter(array(
                        'position > '.$this->position,
                        'parent_id = '.$this->parent_id,
                        $condition,
                    ))),
                ));
                
                // assign children to new parent
                $models=$this->accessible()->findAll('parent_id=:parent',array(':parent'=>$this->id));
                if($models){
                    $models2=$this->accessible()->findAll('parent_id=:parent',array(':parent'=>$this->parent_id));
                    $count=count($models2);
                    foreach($models as $data){
                        $data->saveAttributes(array('parent_id'=>$this->parent_id, 'position'=>++$count));
                    }
                }
                break;
        }//end switch
    }    
    
    protected function uploadImages($attribute='image_'){
        $model=new Gallery;
        $model->moduleId_=$this->id;
        $model->module_=get_class($this);
        $model->file_=$this->$attribute;
        if ($model->addRecord()) {
            //$this->dataLog[get_class($model)]=$model->attributes;
        }else
            $this->addErrors($model->getErrors());
    }
    
    protected function uploadImageUrls($attribute='imageUrl_'){
        $model=new Gallery;
        $model->moduleId_=$this->id;
        $model->module_=get_class($this);
        $model->url_=$this->$attribute;
        if($model->addUrlRecord()){
            //$this->dataLog[get_class($model)]=$model->attributes;
        }else{
            $this->addErrors($model->getErrors());
        }
    }
    
    protected function updateImageEditor($attribute='imageEditor_'){
        $model=new Gallery;
        $model->moduleId_=$this->id;
        $model->module_=get_class($this);
        $model->captions_=$this->$attribute;
        if($model->updateCaptions())
            $this->dataLog[get_class($model)]=$model->attributes;
        else
            $this->addErrors($model->getErrors());
    }
    
    protected function uploadFiles($attribute='file_'){
        $model=new File;
        $model->moduleId_=$this->id;
        $model->module_=get_class($this);
        $model->file_=$this->$attribute;
        if($model->addRecord()){
            //$this->dataLog[get_class($model)]=$model->attributes;
        }else
            $this->addErrors($model->getErrors());
    }
    
    protected function uploadVideos($attribute='video_'){
        $model=Video::model();
        $model->moduleId_=$this->id;
        $model->module_=get_class($this);
        $model->file_=$this->$attribute;
        if($model->addRecord()){
            //$this->dataLog[get_class($model)]=$model->attributes;
        }else
            $this->addErrors($model->getErrors());
    }
    
    protected function updateVideoEditor($attribute='videoEditor_'){
        $model=Video::model();
        $model->moduleId_=$this->id;
        $model->module_=get_class($this);
        $model->file_=$this->$attribute;
        if($model->updateRecord()){
            //$this->dataLog[get_class($model)]=$model->attributes;
        }else
            $this->addErrors($model->getErrors());
    }
    
    public function updateDependentModel($models){
        foreach($models as $model){
            if($model->isNewRecord){
                if(method_exists($model,'getIsEmptyInput') && $model->isEmptyInput) continue;
                $model->module_=get_class($this);
                $model->moduleId_=$this->id;
            }
            if($model->save(false)){
                $this->dataLog[get_class($model)]=$model->attributes;
            }else{
                $this->addErrors($model->getErrors()); break;
            }
        }
    }
    
    public function addRecord(){
        $this->beginTransaction();
        try{
            if($this->save(false)){
                $this->dataLog[get_class($this)]=$this->attributes;
                $this->updateDependentModel(func_get_args());
                if(!empty($this->image_)) $this->uploadImages('image_');
                if(!empty($this->video_)) $this->uploadVideos ('video_');
                if(!empty($this->file_)) $this->uploadVideos ('file_');
            }
            if($this->hasErrors()){
                $this->rollback();
                return false;
            }else{
                $this->commit();
                $this->saveLog();
                return true;
            }
        } catch (Exception $ex) {
            $this->rollback();
        }
    }
    
    public function updateRecord(){
        $this->beginTransaction();
        try{
            if($this->save(false)){
                $this->dataLog[get_class($this)]=$this->attributes;
                $this->updateDependentModel(func_get_args());
                if($this->image_)$this->uploadImages ('image_');
                if(!empty($this->imageEditor_))$this->updateImageEditor();
                if(!empty($this->video_)) $this->uploadVideos('video_');
                if(!empty($this->videoEditor_)) $this->updateVideoEditor();
            }
            if($this->hasErrors()){   
                $this->rollback();
                return false;
            }else{
                $this->commit();
                $this->saveLog();
                return true;
            }
        } catch (Exception $ex) {
            $this->rollback();
        }
    }
    
    public function deleteRecord(){
        $this->status_code=Option::STATUS_DELETED;
        $this->dataLog[get_class($this)]=$this->attributes;
        if($this->save(false)){
            $this->saveLog();
            return true;
        }else
            return false;
    }
    
    public function saveLog() {
        if (Yii::app()->params['logUserActivityMode'] && in_array($this->scenario,array(
            'adminRegister', 'adminCreate', 'adminUpdate', 'adminDelete', 
            'userRegister', 'userCreate', 'userUpdate', 'userDelete',
        ))) {
            $model = new ActivityLog('register');
            $model->module_ = get_class($this);
            $model->moduleId_ = $this->id;
            $model->moduleStatus_ = $this->statusCode;
            $model->scenario_ = $this->scenario;
            $model->attributes_ = $this->dataLog;
            if ($model->save(true)) {
                if(Yii::app()->controller->debugMode)
                    $model->addError('error', 'function Name: '.__FUNCTION__);
                $this->addErrors($model->getErrors());
            }
        }//endif
    }
    
    public function saveViewLog(){
        $model=new ViewLog('create');
        $model->module_ = get_class($this);
        $model->moduleId_ = $this->id;
        $model->language_=$this->defaultLanguage;        
        if (!$model->save(true)) {
            $this->addErrors($model->getErrors());
        }
    }
    
    public function saveBrowserLog(){
        if (Yii::app()->params['logBrowserMode']) {
            $model = new BrowserLog('register');
            $model->module_ = get_class($this);
            $model->moduleId_ = $this->id;
            if (!$model->save(true)) {
                $this->addErrors($model->getErrors());
            }
        }//endif
    }
    
    public function getId() {
        return CHtml::encode($this->id);
    }
    
    public function selectiveDefaultImage($value, $options=array()){
        if(!is_array($options)) return ;
        return $this->defaultImage=isset($options[$value])? $options[$value]: null;
    }
    public function selectiveValue($value, $options=array()){
        if(!is_array($options)) return ;
        return isset($options[$value])? $options[$value]: null;
    }
    
    public function getHasThumbnail(){
        return !empty($this->photo);
    }
    
    public function getDefaultImage(){
        if(is_array($this->defaultImage) && !empty($value)){
            return isset($this->defaultImage[$value])? $this->defaultImage[$value]:null;
        }else
            return $this->defaultImage;
    }
    
    public function getSquareThumbnail($value=null){
        return empty($this->photo)? $this->getDefaultImage():$this->photo->squareThumbnail;
    }
    
    public function getLargeSquareThumbnail($value=null){
        return empty($this->photo)? $this->getDefaultImage():$this->photo->largeSquareThumbnail;
    }
    
    public function getThumbnail($value=null){
        return empty($this->photo)? $this->getDefaultImage():$this->photo->thumbnail;
    }
    
    public function getSmallThumbnail($value=null){
        return empty($this->photo)? $this->getDefaultImage(): $this->photo->smallThumbnail;
    }
    
    public function getMediumThumbnail($value=null){
        return empty($this->photo)? $this->getDefaultImage():$this->photo->mediumThumbnail;
    }
    
    public function getOriginalFile(){
        return empty($this->photo)? $this->getDefaultImage():$this->photo->mediumThumbnail;
    }
    
    public function getThumbnailWidth(){
        return empty($this->photo) ? null : $this->photo->width;
    }
    
    public function getThumbnailHeight(){
        return empty($this->photo) ? null : $this->photo->height;
    }
    
    public function resizeWidthByHeight($newHeight, $width, $height){
        if(empty($width)) $width = 1;
        if(empty($height)) $height = 1;
        return ceil(($newHeight/ $width) * $height);
    }
    
    public function resizeHeightByWidth($newWidth, $width, $height){
        if(empty($width)) $width = 1;
        if(empty($height)) $height = 1;
        return ceil(($newWidth/ $width) * $height);
    }
    
    public function getThumbnailWidthRatio($width){
        $value = $this->thumbnailWidth;
        if(empty($value)) return 0;
        return ceil($width/ $value);
    }
    
    public function getThumbnailHeightRatio($height){
        $value = $this->thumbnailHeight;
        if(empty($value)) return 0;
        return ceil($height/ $value);
    }
    
    public function getThumbnailCaption() {
        return empty($this->photo) ? null : $this->photo->caption;
    }
    
    /**
     * Embed video
     * @return type
     */
    public function setEmbedVideoDimension($width=null, $height=null){
        if(!empty($this->video)){
            if(!empty($width)) $this->video->defaultWidth=$width;
            if(!empty($height)) $this->video->defaultHeight=$height;
        }
    }
    
    public function getEmbedVideo(){
        if(empty($this->video))
            return CHtml::image($this->defaultImage,'', array(
                'width'=>$this->defaultWidth,
                'height'=>$this->defaultHeight,
            ));
        else{
            return $this->video->embedHtml;
        }
    }
    
    public function getEmbedVideoThumbnail($htmlOptions=array()){
        if(empty($this->video)){
            if(is_array($this->defaultImage)){
                $this->defaultImage=isset($htmlOptions['value']) && isset($this->defaultImage[$htmlOptions['value']])? 
                        $this->defaultImage[$htmlOptions['value']]:null;
            }
            return CHtml::image($this->defaultImage,'', array(
                'width'=>$this->defaultWidth,
                'height'=>$this->defaultHeight,
            ));
        }else{
            return $this->video->thumbnail;
        }
    }
    
    public function getEmbedVideoCaption(){
        return empty($this->video)? $this->video->fileCaption:null;
    }
    
    
    /**
     * Content functions
     */
    public function br2nl($content){
        //return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $content);
        return preg_replace('/\<br(\s*)?\/?\>/i', '', $content);
    }
    
    public function getTitle() {
        if(empty($this->html)){
            return empty($this->defaultHtml)? null:html_entity_decode($this->defaultHtml->title);
        }else{
            return html_entity_decode($this->html->title);
        }
    }

    public function getDescription(){       
        if(empty($this->html)){
            return empty($this->defaultHtml)? null:html_entity_decode($this->defaultHtml->description);
        }else{
            return html_entity_decode($this->html->description);
        }
    }
    
    public function getContent() {
        if(empty($this->html)){
            return empty($this->defaultHtml)? null:html_entity_decode($this->defaultHtml->fullContent);
        }else{
            return html_entity_decode($this->html->fullContent);
        }
    }

    public function getSefUrl() {
        return empty($this->html)?
            empty($this->defaultHtml)? null:$this->defaultHtml->sefUrl
            : $this->html->sefUrl;
    }

    public function getMetaTitle() {       
        if(empty($this->html)){
            return empty($this->defaultHtml)? null: html_entity_decode($this->defaultHtml->metaTitle);
        }else{
            return html_entity_decode($this->html->metaTitle);
        }        
    }

    public function getMetaDescription() {
        if(empty($this->html)){
            return empty($this->defaultHtml)? null:html_entity_decode($this->defaultHtml->metaDescription);
        }else{
            return html_entity_decode($this->html->metaDescription);
        }
    }

    public function getMetaKeywords() {
        if(empty($this->html)){
            return empty($this->defaultHtml)? null:html_entity_decode($this->defaultHtml->metaKeywords);
        }else{
            return html_entity_decode($this->html->metaKeywords);
        }
    }
    
    /**
     * Address model functions
     */    
    public function getFullAddress(){
        return empty($this->address)? null: $this->address->fullAddress;
    }
        
    public function getAddressCity(){
        return empty($this->address)? null: $this->address->city;
    }
    
    public function getAddressProvince(){
        return empty($this->address)? null: $this->address->province;
    }
    
    public function getAddressState(){
        if(empty($this->address)) return null;
        return $this->address->state == '-'?null:$this->address->stateName;
    }
    
    public function getAddressCountry(){
        return empty($this->address)? null: $this->address->country;
    }
    
    public function getAddressLatitude(){
        return empty($this->address)? null: $this->address->latitude;
    }
    
    public function getAddressLongitude(){
        return empty($this->address)? null: $this->address->longitude;
    }
    
    public function updateCommentCounter(){
        return $this->updateCounters(array('total_comment'=>1), 'id=:id', array(':id'=>$this->id));
    }
    
    public function getTotalView(){
        return empty($this->total_view)? 0: $this->total_view;
    }
    
    public function updateViewCounter(){
        $this->beginTransaction();
        try{
            if($this->updateCounters(array('total_view'=>1), 'id=:id', array(':id'=>$this->id))){
                $this->saveViewLog();
            }
            if($this->hasErrors()){
                $this->rollback();
                return false;
            }else{
                $this->commit();
                return true;
            }
        }catch(Exception $e){
            $this->rollback();
            return false;
        }
    }
    
    /**
     * JSON
     */
    private $_jsonPath;
    public function getJsonPath(){
        if($this->_jsonPath !==null) return $this->_jsonPath;
        return $this->_jsonPath = implode('/', array_filter(array(
            str_replace(Yii::app()->params['mediaDomain'], Yii::app()->params['relativeMediaPath'], $uploadPath=Yii::app()->params['jsonPath']),
        )));
    }
    
    public function createJsonFile($content, $fileName=null){
        if($fileName===null || empty($content)) return;
        
        $path = $this->getJsonPath();
        if(!file_exists($path)){
            if(!mkdir($path, 0777, true)){
                $errors[]='Directory: "'.$path.'" not exist.';
                return false;
            }
        }
        if (!is_writable($path) && !chmod($path, 0777)) {
            $errors[] = "The directory \"" . $path . "\" is not writable";
            return false;
        }
        
        $fileName = $path.'/'.strtolower($fileName).'.json';
        if (!$handle = fopen($fileName, 'w')) {
            $errors[] = "Cannot open file '" . $fileName . "'";
            fclose($handle);
            return false;
        }    
        return file_put_contents($fileName, CJSON::encode($content));
    }
    
    public function readJsonFile($fileName=null){
        if($fileName===null) return;
        $path=$this->getJsonPath();
        $fileName=$path.'/'.strtolower($fileName).'.json';
        return file_exists($fileName)? CJSON::decode(file_get_contents($fileName)) : false;
    }
    
    public function filterKeywords($keywords){
        //return preg_split("/[\s,]+/", $keywords);
        return preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|" . "[\s,]*'([^']+)'[\s,]*|" . "[\s,]+/", $keywords, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    }
    
    public function findAllAccessible($isDataProvider=true){
        $criteria = new CDbCriteria;
        $t = $this->getTableAlias(false);
        
        if($isDataProvider){
            return new ActiveDataProvider($this->accessible(), array(
                'criteria' => $criteria,
            ));
        }else{
            return $this->accessible()->findAll($criteria);
        }
    }
    
    /**
     * Hash tag function
     * @param string $string
     * @return string
     */
    public function createHashTagLink($string){ 
        preg_match_all('/\B#\w*[a-zA-Z]+\w*/',$string,$matches);
        //preg_match_all('/(?<!\w)#\w+/',$string,$matches);
        $hashTags = array();
        foreach($matches[0] as $key=>$tag){
            $hashTags[$tag]=CHtml::link($tag, Yii::app()->createUrl('site/searchresult', array('keywords_'=>$tag)));
        }
        return strtr($string, $hashTags);
    }
    
    /**
     * 
     * @param string $string
     * @return array
     */
    public function getHashTagArray($string){
        preg_match_all('/(?<!\w)#\w+/',$string,$matches);
        $hashTags = array();
        foreach($matches[0] as $key=>$tag){
            $hashTags[$tag]=CHtml::link($tag, Yii::app()->createUrl('site/searchresult', array('keywords_'=>$tag)));
        }
        return $hashTags;
    }
    
    /**
     * SQL debug
     */
    public function criteriaToSQL($model, $criteria, $showParams=true){
        if($showParams) {
            $params = array();
            foreach ($criteria->params as $key => $value) {
                $params[$key] = is_string($value) ? "'" . $value . "'" : $value;
            }
            return str_replace(array_keys($params), array_values($params), $model->getCommandBuilder()->createFindCommand($model->getTableSchema(), $criteria)->getText());
        } else {
            return $model->getCommandBuilder()->createFindCommand($model->getTableSchema(), $criteria)->getText();
        }
    }
    
    public function debugSql($mode = 'select', $criteria = null, $showParams = true) {

        $get = Yii::app()->request->getParam('debug');
        //if(empty($get) || !in_array($get, array('sql')))	return;

        if (empty($criteria))
            $criteria = $this->dbCriteria;

        $builder = $this->getCommandBuilder();

        switch (strtolower($mode)) {

            case 'select':
                $command = $builder->createFindCommand($this->getTableSchema(), $criteria);
                break;

            case 'insert':
                $command = $builder->createInsertCommand($this->getMetaData()->tableSchema, $this->getAttributes());
                break;

            case 'update':
                $params = array();
                $i = 0;
                foreach ($this->attributes as $key => $value) {
                    $params[':yp' . $i++] = $value;
                }//end foreach

                $criteria = $builder->createPkCriteria($this->getTableSchema(), $this->getPrimaryKey(), '', $params);
                $command = $builder->createUpdateCommand($this->getTableSchema(), $this->getAttributes(), $criteria);
                break;

            case 'delete':
                $command = $builder->createDeleteCommand($this->getTableSchema(), $criteria);
                break;
            default:
                return;
                break;
        }//end switch

        $params = $criteria->params;

        print_r($params);

        print_r($this->attributes);

        foreach ($params as $key => $value) {
            if (is_string($value))
                $params[$key] = "'" . $value . "'";
        }
        echo str_replace(array_keys($params), array_values($params), $command->getText());

        /*
          if($showParams){
          $params = array();
          foreach ($criteria->params as $key => $value) {
          $params[$key] =  is_string($value)? "'" . $value . "'" : $value;
          }
          return str_replace(array_keys($params), array_values($params), $model->getCommandBuilder()->createFindCommand($model->getTableSchema(), $criteria)->getText());
          } else {
          return $model->getCommandBuilder()->createFindCommand($model->getTableSchema(), $criteria)->getText();
          } */

        /*
          if($showParams){
          for($i = count($criteria->params) - 1; $i >= 0; $i--){
          $key = ':yp' . $i;
          $sqlStatement = preg_replace('/' .$key.'/i', is_numeric($criteria->params[$key])? $criteria->params[$key]: "'".$criteria->params[$key] . "'" , $sqlStatement);
          }//end for
          }//end if
         */
        //echo $sqlStatement;
    }

    public function saveFormSearchCriterias(){
        if(!Yii::app()->request->isPostRequest) return array();
        $params=array_filter(Yii::app()->request->getParam(get_class($this),array()));
        if($params){
            $search=new SearchLog;
            $search->criteria_=$params;
            if($search->addRecord()){
                $params['sid']=$search->id;
            }
        }
        return $params;
    }
    
    public function getFormSearchCriterias(){
        $form=Yii::app()->request->getParam(get_class($this));
        $searchId=Yii::app()->request->getParam('sid');
        if($searchId){
            $search=SearchLog::model()->findByPk($searchId);
            $form=$search?$search->criteriaContent:array();
        }elseif(empty($form)){
            $form=array_filter($_GET);
        }
        return $this->attributes=$form;
    }
    
}//end class